package Socket;

import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private int port;
    private String serverIp;
    private DatagramSocket socket;

    public UdpEchoClient(Integer port, String serverIp) throws SocketException {
        this.port = port;
        this.serverIp = serverIp;
        this.socket = new DatagramSocket();
    }

    public void start() throws Exception{
        while (true){
            System.out.println("请输入要发送的内容： ");
            Scanner in=new Scanner(System.in);
            if (!in.hasNext())break;
            String str=in.nextLine();
            DatagramPacket requestpacket=new DatagramPacket(str.getBytes(),str.getBytes().length,
                    InetAddress.getByName(serverIp),port);
            socket.send(requestpacket);
            DatagramPacket reponsePacket=new DatagramPacket(new byte[1024],1024);
            socket.receive(reponsePacket);
            System.out.println(new String(reponsePacket.getData(),0,reponsePacket.getLength()));
        }
        }

    public static void main(String[] args) throws Exception {
        UdpEchoClient client=new UdpEchoClient(8888,"127.0.0.1");
        client.start();
    }
}
